<template>
  <!-- 供应商分类 -->
  <MainSlot>
    <template v-slot:searchForm>
      <SearchForm :formItemList="formItemList" @search="(e) => {
          (searchlist = { ...e }), (currentPage = 1), getTableDataList();
        }
        ">
      </SearchForm>
    </template>
    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>
    <template v-slot:table>
      <TableData :isSelect="true" :tableThead="tableThead" :dataList="dataList" :config="table_config"
        @selection-change="selectionChange">
      </TableData>
    </template>
    <template v-slot:pagination>
      <Pagination @size-Change="changePageSize" :size="pageSize" @current-change="handleCurrentChange"
        :page="currentPage" :total="total">
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <el-dialog :close-on-click-modal="false" :title="titleText" :visible.sync="dialogFormVisible"
        @close="cancel('formData')">
        <el-form ref="formData" label-position="left" :model="formData" :rules="rules" class="el-form">
          <el-form-item v-for="item, index in formDatalists" :key="index" :label="item.name + ':'" :prop="item.prop"
            class="w50p" :rules="[
              { required: item.required, message: item.name + '不能为空', trigger: item.type === 'input' ? 'blur' : 'change' }
            ]">
            <el-input v-if="item.type === 'input'" v-model="formData[`${item.prop}`]" :placeholder="'请输入' + item.name"
              clearable />
            <el-select v-if="item.type === 'Select'" v-model="formData[`${item.selectValue}`]" filterable
              :placeholder="'请选择' + item.name" clearable>
              <el-option v-for="items, indexs in item.typeObj.list" :key="indexs" :label="items.name"
                :value="items.value" />
            </el-select>
            <el-date-picker v-if="item.type === 'TimePicker'" v-model="formData[`${item.prop}`]" type="date"
              value-format="yyyy-MM-dd" :placeholder="'选择' + item.name" />
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button class="zh-button-two" type="primary" @click="save('formData')">保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </MainSlot>
</template>
<script>
import MainSlot from "@/components/MainSlot";
import Pagination from "@/components/Pagination";
import SearchForm from "@/components/SearchForm";
import TableData from "@/components/TableData";
import BtnSlot from "@/components/BtnSlot";

import customerTypeApi from "@/api/livestock-manage/sale-manage/customerType";
import { mymixin } from "@/utils/mixins";
import { mapGetters } from "vuex";
export default {
  name: "AgrInputManagementtwo",
  components: { SearchForm, TableData, BtnSlot, Pagination, MainSlot },
  mixins: [mymixin],
  data() {
    return {
      total: 100,
      selectIndex: 0,
      currentPage: 1,
      dataList: [],
      selectionList: [],
      formItemList: [
        {
          label: "客户类型名称",
          type: "input",
          param: "customerTypeName",
          isShow: true,
        },
      ],
      btnList: ["add", "delete"],
      tableThead: [
        { isShow: true, label: "客户类型名称", prop: "customerTypeName" },
        { isShow: true, label: "备注", prop: "remarks" },
      ],
      // 配置项
      table_config: {
        isCheckBox: true,
        isOperation: true,
        // 表格操作列
        operation: {
          label: "操作",
          width: "200",
          cols: [
            {
              label: "编辑",
              type: "primary",
              flag: "edit",
              handleRow: this.handleRow,
            },
            {
              label: "删除",
              type: "danger",
              flag: "delete",
              handleRow: this.handleRow,
            },
          ],
        },
      },
      // type为Select时需要添加selectValue
      formDatalists: [
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "customerTypeName",
          typeObj: {
            list: []
          },
          name: "客户类型名称",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "remarks",
          typeObj: {
            list: []
          },
          name: "备注",
          notSearch: true
        }
      ],
      // =====================下面可能是用不上的，但是不敢删
      tableColumn: [
        { prop: "customerTypeName", label: "供应商类型" },
        { prop: "remarks", label: "备注" },
        {
          prop: "operation",
          label: "操作",
          slotName: "operation",
          width: "120",
        },
      ],
      searchlist: {},
      formConfig: [
        {
          label: "供应商类型名称",
          prop: "customerTypeName",
          type: "input",
        },
      ],
      dialogTitle: null,
      dialogFormVisible: false,
      // 新增的规则校验
      isshowmessage: false,
      rules: {
        customerTypeName: [
          {
            required: true,
            message: "请输入供应商类型名称",
            trigger: "change",
          },
        ],
      },
      formData: {},
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission",
    }),
  },
  watch: {
    nowChanceStau(newval) {
      this.isshowmessage = !!newval;
    },
    dialogFormVisible(v) {
      if (v) {
        this.$nextTick(() => {
          this.$refs["formData"].clearValidate();
        });
      }
    },
  },
  mounted() {
    this.getTableDataList();
  },
  methods: {
    // 多选方法
    selectionChange(val) {
      this.selectionList = val || [];
    },
    handleCurrentChange(val) {
      console.log(val);
      this.currentPage = val;
      this.getTableDataList();
    },
    //获取选中Btn
    getBtnEvent(flag) {
      console.log(flag);
      if (flag == "add") {
        this.add();
      } else if (flag == "delete") {
        if (this.selectionList.length > 0) {
          this.handleDelete(this.selectionList);
        } else {
          this.$message.warning("请先选择表单数据项后再删除！");
        }
      }
      this.addEditFlag = flag;
    },
    add() {
      this.formData = {};
      this.openDialog("add");
    },
    cancel() {
      this.closeDialog();
      this.formData = {};
    },
    openDialog(type) {
      this.dialogFormVisible = true;
      this.dialogTitle = type === "add" ? "新增" : "编辑";
      this.nowChanceStau = type;
    },
    closeDialog() {
      this.dialogFormVisible = false;
      this.dialogFormAssignVisible = false;
      this.dialogTitle = null;
      this.nowChanceStau = "";
    },
    // 操作方法
    handleRow(rowData, item) {
      if (item.flag == "edit") {
        this.dialogFormVisible = true;
        this.nowChanceStau = "edit";
        this.formData = JSON.parse(JSON.stringify(rowData));
      } else if (item.flag == "delete") {
        this.nowChanceStau = "del";
        this.handleDelete([rowData]);
      }
      this.addEditFlag = item.flag;
    },
    // 获取当前表格信息
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        // sortList: this.sortList || [],
        entity: {
          ...this.searchlist,
          organizationNo: sessionStorage.organizationNo,
        },
      };
      this.entity = params.entity;
      customerTypeApi.pageQuery(params).then((res) => {
        this.loading = false;
        if (res.code !== 1) {
          this.$message.error(res.msg);
          return;
        }
        let data = res.data;
        this.dataList = data.content || [];
        this.total = data.totalElements;
      });
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },

    // 表格点击
    handleEdit(list) {
      this.formData = { ...list };
      this.openDialog("edit");
    },
    handleSelectionChange(list) {
      this.selectIdList = [];
      this.selectIdList = list.map((item) => {
        return item.supplierTypeNo;
      });
      if (this.selectIdList && this.selectIdList.length > 0) {
        this.delActive = true;
      } else this.delActive = false;
    },

    handleDelete(list) {
      let selectedStaffList = [];
      list.forEach((item) => {
        selectedStaffList.push(item.customerTypeNo);
      });
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          let params = {
            noList: selectedStaffList,
          };
          console.log(params);
          customerTypeApi.numberBatchDel(params).then((res) => {
            if (res.code === 1) {
              this.$message.success("删除成功");
              this.getTableDataList();
            } else {
              this.$message.error("删除失败");
            }
          });
        })
        .catch(() => {
          this.$message("取消删除");
        });
    },
    save() {
      this.$refs["formData"].validate((valid) => {
        if (valid) {
          if (this.nowChanceStau === "add") {
            let parone = {
              ...this.formData,
              organizationNo: sessionStorage.organizationNo,
            };
            customerTypeApi.add(parone).then((res) => {
              if (res.code === 1) {
                this.closeDialog();
                this.getTableDataList();
                this.$message.success("添加成功");
              } else {
                this.$message.error("添加失败");
              }
            });
          }
          if (this.nowChanceStau === "edit") {
            let params = {
              ...this.formData,
            };
            customerTypeApi.edit(params).then((res) => {
              if (res.code === 1) {
                this.closeDialog();
                this.getTableDataList();
                this.$message.success("修改成功");
              } else {
                this.$message.error("修改失败");
              }
            });
          }
        } else {
          this.$message.warning("请填写完整！！！");
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.tabhid {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  // background-color: #0cb28c;
}

.zhtabletitle {
  color: #31f7dd;
  margin-bottom: 10px;
}

::v-deep .staff-manage .common-layout .content {
  overflow-y: auto;
}

.upimg {
  ::v-deep .xunzeimage {
    width: 140px !important;
  }
}

.dialog {
  img {
    width: auto;
    max-width: 100%;
  }
}

::v-deep .el-upload--picture-card {
  width: 40px;
  height: 40px;
  background-color: rgba(255, 255, 255, 0.1);
  border: 1px solid #6ecae3;
}

::v-deep .el-upload--picture-card {
  position: relative;
}

::v-deep .el-upload--picture-card .el-icon-plus {
  font-size: 34px;
  color: #6ecae3;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

::v-deep .el-dialog__body {
  height: 90%;
  text-align: center;
  // img {
  //   width: 100%;
  // }
}

::v-deep .el-upload__tip {
  display: none;
}

::v-deep .el-form {
  display: flex;
  //   .el-form-item__label {
  //     min-width: 130px !important;
  //   }
}

.w50p {
  padding: 10px;
  display: flex;
}
</style>
